import React from "react";
import {render} from "react-dom";
import {state, connect} from "noflux";
var noop = function () {};

require('./index.css');
var types = [
  'return-direct',
  'replace-res'
];

function getType() {
  var type = state.get('type');
  if (type) return type;
  return types[0];
}

function getEntries() {
  var type = getType();
  return state.get(`${type}.entries`) || [];
}

function setEntries(entries) {
  var type = getType();
  return state.set(`${type}.entries`, entries || []);
}

function setEntry(t, value) {
  var type = getType();
  var index = state.get('index');
  if (type === void 0 || index === void 0) alert(JSON.stringify({type, index}));
  state.set(`${type}.entries.${index}.${t}`, value);
  //console.log('seting ' + `${type}.entries.${index}.${t}`, value);

  fetch("/api/config/" + getType(), {
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        index,
        key: t,
        pattern: getPattern(),
        value: value || ''
      })
  })
  .then((res) => void 0)
}
function getEntry() {
  var type = getType();
  var index = state.get('index');
  return state.get(`${type}.entries.${index}`) || {};
}
function setIndex(index) {
  state.set('index', index);
}
function getIndex() {
  var index = state.get('index', index);
  if (index === void 0 ) {
    var entries = getEntries() || [];
    if (!entries.length) return;
    index = 0;
    state.set('index', 0);
  }
  return index
}
function getPattern() {
  var entry = getEntry();
  return (entry || {}).pattern || '';
}

function loadEntries(type) {
   state.set('type', type);
   fetch(`/api/config/${type}`)
     .then(res => res.json())
     .then(arr => state.set(`${type}.entries`, arr || []));
}

class App extends React.Component {
  create() {
    var pattern = prompt('enter pattern');
    var entries = getEntries();
    setEntries(entries.concat({
      pattern,
      content: ''
    }));
  }
  render() {
    return (
    <div>
      类型:
      <select value={getType()} onChange={e => loadEntries(e.target.value)} >
        {types.map(t => <option value={t}>{t}</option>)}
      </select>

     条目:
      <select value={getIndex()} onChange={e => setIndex(e.target.value)} >
      {
        getEntries().map((x, i) => 
          <option key={x.pattern + i} value={i}>{x.pattern}</option>
        )
      }
      </select>
      <input value={getPattern()} onChange={e => setEntry('pattern', e.target.value)} />
      <button onClick={() => this.create()}>新增</button>
      <div>
        <textarea className="t" value={getEntry().content || ''} onChange={e => setEntry('content', e.target.value)}></textarea>
      </div>
    </div>
    )
  }
}

connect(App);
state.set('type', types[0]);
loadEntries(types[0]);

window.state = state;

render(<App />, document.getElementById('app'));
